#include <QCryptographicHash>
#include <QClipboard>
#include <QEvent>
#include <QApplication>

#include <utils/clipboardwatcher.h>



namespace utils {
QString ClipboardWatcher::generateHash(const QString &data) {
	QCryptographicHash hash(QCryptographicHash::Sha256);
	hash.addData(data.toUtf8());
	return hash.result().toHex();
}

ClipboardWatcher::ClipboardWatcher(QObject *parent) : QObject(parent) {
	qApp->installEventFilter(this);
	timer.setSingleShot(true);
	connect(&timer, &QTimer::timeout, this, &ClipboardWatcher::clearClipboard);
}

void ClipboardWatcher::setClipboardData(const QString &data) {
	QClipboard *clipboard = qApp->clipboard();
	clipboard->setText(data);
	clipboardHash = generateHash(data);
	startTimer();
}

bool ClipboardWatcher::eventFilter(QObject *obj, QEvent *event) {
	if (event->type() == QEvent::KeyPress) {
		QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
		if (keyEvent->matches(QKeySequence::Copy) ||  // Ctrl+C on Windows/Linux и Cmd+C на macOS
			keyEvent->matches(QKeySequence::Cut)) {   // Ctrl+X на Windows/Linux и Cmd+X на macOS
			QClipboard *clipboard = qApp->clipboard();
			clipboardHash = generateHash(clipboard->text()); // Сохранение хеша текущих данных буфера обмена
			startTimer();
		}
	}
	return QObject::eventFilter(obj, event);
}

void ClipboardWatcher::startTimer() {
	timer.start(7000); // 7 seconds
}

void ClipboardWatcher::clearClipboard() {
	QClipboard *clipboard = qApp->clipboard();
	if (clipboardHash == generateHash(clipboard->text())) {
		clipboard->clear();
		emit clipboardCleared();
	}
}
}